package org.ofbiz.wvtools.wxutil;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilValidate;

import com.alibaba.fastjson.JSONObject;

/**
 * Created by wangwei on 18/9/18.
 */
public class HttpUtils {

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
	String result = "";
	BufferedReader in = null;
	try {
	    String urlNameString = url + "?" + param;
	    System.out.println(urlNameString);
	    URL realUrl = new URL(urlNameString);
	    // 打开和URL之间的连接
	    URLConnection connection = realUrl.openConnection();
	    // 设置通用的请求属性
	    connection.setRequestProperty("accept", "*/*");
	    connection.setRequestProperty("connection", "Keep-Alive");
	    connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	    // 建立实际的连接
	    connection.connect();
	    // 定义 BufferedReader输入流来读取URL的响应
	    in = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));

	    String line;
	    while ((line = in.readLine()) != null) {
		result += line;
	    }
	} catch (Exception e) {
	    Debug.logError("发送GET请求出现异常！" + e.getMessage(), "HttpUtils");
	}
	// 使用finally块来关闭输入流
	finally {
	    try {
		if (in != null) {
		    in.close();
		}
	    } catch (Exception e2) {
		Debug.logError(e2.getMessage(), "HttpUtils");
	    }
	}
	return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
	PrintWriter out = null;
	BufferedReader in = null;
	String result = "";
	try {
	    URL realUrl = new URL(url);
	    // 打开和URL之间的连接
	    URLConnection conn = realUrl.openConnection();
	    // 设置通用的请求属性
	    conn.setRequestProperty("accept", "*/*");
	    conn.setRequestProperty("connection", "Keep-Alive");
	    conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	    // 发送POST请求必须设置如下两行
	    conn.setDoOutput(true);
	    conn.setDoInput(true);
	    // 获取URLConnection对象对应的输出流
	    out = new PrintWriter(conn.getOutputStream());
	    // 发送请求参数
	    out.print(param);
	    // flush输出流的缓冲
	    out.flush();
	    // 定义BufferedReader输入流来读取URL的响应
	    in = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.forName("UTF-8")));
	    String line;
	    while ((line = in.readLine()) != null) {
		result += line;
	    }
	} catch (Exception e) {
	    System.out.println("发送 POST 请求出现异常！" + e);
	    e.printStackTrace();
	}
	// 使用finally块来关闭输出流、输入流
	finally {
	    try {
		if (out != null) {
		    out.close();
		}
		if (in != null) {
		    in.close();
		}
	    } catch (IOException ex) {
		ex.printStackTrace();
	    }
	}
	return result;
    }

    public static String httpPostRequest(String url, Map<String, Object> map) {
	JSONObject jsonParam = new JSONObject(map);
	Debug.log("request post url : " + url + "   paramMap : " + jsonParam.toString());

	String result = "";
	try {
	    // 忽略证书
	    CloseableHttpClient httpClient = createSSLClientDefault();
	    // 创建httpClient实例
//		      CloseableHttpClient httpClient = HttpClients.createDefault();
	    // 创建httpPost远程连接实例
	    HttpPost httpPost = new HttpPost(url);
	    // 配置请求参数实例
	    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000)// 设置连接主机服务超时时间
		    .setConnectionRequestTimeout(10000)// 设置连接请求超时时间
		    .setSocketTimeout(30000)// 设置读取数据连接超时时间
		    .build();
	    // 为httpPost实例设置配置
	    httpPost.setConfig(requestConfig);
	    // 设置请求头
	    httpPost.addHeader("content-type", "application/json;charset=utf-8");
	    // 封装post请求参数
	    httpPost.setEntity(new StringEntity(jsonParam.toJSONString(), Charset.forName("UTF-8")));
//		      // 从响应对象中获取响应内容
//		      result = EntityUtils.toString(httpResponse.getEntity());
	    CloseableHttpResponse response = httpClient.execute(httpPost);
	    StatusLine status = response.getStatusLine();
	    int state = status.getStatusCode();
	    if (state == HttpStatus.SC_OK) {
		result = EntityUtils.toString(response.getEntity());
	    } else {
		result = EntityUtils.toString(response.getEntity());
		// Debug.logError("请求返回:" + state, module);
	    }
	} catch (UnsupportedEncodingException e) {
	    // Debug.logError(e.getMessage(), module);
	} catch (IOException e) {
	    // Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    public static String httpPostRequest(String url, JSONObject jsonParam) {
	if(UtilValidate.isNotEmpty(jsonParam)) {
	    Debug.log("request post url : " + url + "   paramMap : " + jsonParam.toString());
	    System.out.println(jsonParam.toString());
	}
	String result = "";
	try {
	    CloseableHttpClient httpClient = createSSLClientDefault();
	    HttpPost httpPost = new HttpPost(url);
	    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000)// 设置连接主机服务超时时间
		    .setConnectionRequestTimeout(10000)// 设置连接请求超时时间
		    .setSocketTimeout(30000)// 设置读取数据连接超时时间
		    .build();
	    // 为httpPost实例设置配置
	    httpPost.setConfig(requestConfig);
	    
	    // 设置请求头
	    httpPost.addHeader("content-type", "application/json;charset=utf-8");
	    // 封装post请求参数
	    if(UtilValidate.isNotEmpty(jsonParam)) {
		httpPost.setEntity(new StringEntity(jsonParam.toJSONString(), Charset.forName("UTF-8")));
	    }
//    		      // 从响应对象中获取响应内容
	    CloseableHttpResponse response = httpClient.execute(httpPost);
	    StatusLine status = response.getStatusLine();
	    int state = status.getStatusCode();
	    if (state == HttpStatus.SC_OK) {
		result = EntityUtils.toString(response.getEntity());
	    } else {
		result = EntityUtils.toString(response.getEntity());
		// Debug.logError("请求返回:" + state, module);
	    }
	} catch (UnsupportedEncodingException e) {
	    // Debug.logError(e.getMessage(), module);
	} catch (IOException e) {
	    // Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    public static String httpPostUpload(String url, String localFile, String fileParamName) {
	CloseableHttpClient httpClient = createSSLClientDefault();
	String result = "";
	HttpPost httpPost = new HttpPost(url);
	RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000)// 设置连接主机服务超时时间
		.setConnectionRequestTimeout(10000)// 设置连接请求超时时间
		.setSocketTimeout(30000)// 设置读取数据连接超时时间
		.build();
	// 为httpPost实例设置配置
	httpPost.setConfig(requestConfig);
	// 设置请求头
	httpPost.addHeader("content-type", "multipart/form-data");
	try {
	    // 把文件转换成流对象FileBody
	    FileBody bin = new FileBody(new File(localFile));
	    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
	    builder.addPart("files", bin);
	    builder.addPart("filesFileName",new StringBody(fileParamName, ContentType.create("text/plain", Consts.UTF_8)));
//            if (params != null) {
//                for (String key : params.keySet()) {
//                    builder.addPart(key,new StringBody(params.get(key), ContentType.create("text/plain", Consts.UTF_8)));
//                }
//            }

	    HttpEntity reqEntity = builder.build();
	    httpPost.setEntity(reqEntity);

	    // 发起请求 并返回请求的响应
	    CloseableHttpResponse response = httpClient.execute(httpPost, HttpClientContext.create());
	    StatusLine status = response.getStatusLine();
	    int state = status.getStatusCode();
	    if (state == HttpStatus.SC_OK) {
		result = EntityUtils.toString(response.getEntity());
	    } else {
		result = EntityUtils.toString(response.getEntity());
	    }

	} catch (UnsupportedEncodingException e) {
	} catch (IOException e) {
	}
	return result;
    }

    public static CloseableHttpClient createSSLClientDefault() {
	try {
	    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
		// 信任所有证书
		public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		    return true;
		}
	    }).build();
	    SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(sslContext);
	    return HttpClients.custom().setSSLSocketFactory(sslFactory).build();
	} catch (Exception e) {
	    // Debug.logError(e.getMessage(), module);
	}
	return HttpClients.createDefault();
    }
}
